import {message} from "antd";

const url = "wss://www.jxselab.com:8000/"
// const url = "ws://localhost:8000/"
export class Require2FormController {
  constructor(setMessages, setCurrentProgress, setCurrentProgressFina) {
    this.socket = new WebSocket(`${url}ws/sapperchain/require2SPLForm`);
    this.setMessages = setMessages;
    this.setCurrentProgress = setCurrentProgress;
    this.setCurrentProgressFina = setCurrentProgressFina;
    this.initializeWebSocket();
  }

  initializeWebSocket() {
    this.socket.addEventListener('open', () => {

    });

    this.socket.addEventListener('message', (event) => {
      try {
        const messagePart = event.data;
        if(event.data === "__END_OF_RESPONSE__"){
            this.setCurrentProgressFina();
            message.success("All agent skills have been generated");
            // this.socket.close();
        }
        else {
            // 解析 JSON
            const parsedMessage = JSON.parse(messagePart);
            // 更新消息数组
            this.setMessages((prevMessages) => [...prevMessages, parsedMessage]);
            // 更新当前步骤
            this.setCurrentProgress();
        }
      } catch (error) {
        console.error('Error parsing message:', error);
      }
    });


    this.socket.addEventListener('close', () => {
      console.log('WebSocket Disconnected');
      this.setCurrentProgress();
    });

    this.socket.addEventListener('error', (event) => {
      console.error('WebSocket Error: ', event);
    });
  }

  sendMessage(mes) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      message.info("generating");
      this.socket.send(mes);
    }
  }

  close() {
    this.socket.close();
  }
}

export class CompilerController {
  constructor(agent_uuid, setLogInfo, setChain) {
    this.socket = new WebSocket(
      `${url}ws/sapperchain/splcompiler?agent_uuid=${agent_uuid}`
    );
    this.ongoingServerMessage = { content: "", element: null };
    this.setLogInfo = setLogInfo
    this.setChain = setChain
    this.initializeWebSocket();
  }

  initializeWebSocket() {
    this.socket.addEventListener("open", () => {
      console.log("CompilerController Connected");
      this.sendMessage();
    });

    this.socket.addEventListener("message", (event) => {
      try {
        const messagePart = event.data;
        // 解析 JSON

        if (messagePart === "__END_OF_RESPONSE__") {
          // Server message is complete, reset the ongoing server message
          this.setLogInfo("编译结束\n")

          this.ongoingServerMessage = { content: "", element: null };
          this.close();
        } else {
          const response = JSON.parse(messagePart)
          if (response.type === 'logInfo' ) {
            this.setLogInfo(response.content)
          }else {
            this.setChain(response.content)
          }
        }

        // 更新当前步骤
      } catch (error) {
        this.setLogInfo("Error parsing message CompilerController: ", error);
      }
    });

    this.socket.addEventListener("close", () => {
      console.log("WebSocket Disconnected Compiler");
    });

    this.socket.addEventListener("error", (event) => {
      console.error("WebSocket Error Compiler: ", event);
    });
  }
  sendMessage() {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.setLogInfo("开始编译\n")
      // console.log("Compiler Message");
      this.socket.send("1");
    }
  }

  close() {
    this.socket.close();
  }
}

export class RefactorController {
  constructor(agent_uuid, setLogInfo, setSPLForm) {
    this.socket = new WebSocket(
      `${url}ws/sapperchain/splrefactor?agent_uuid=${agent_uuid}`
    );
    this.ongoingServerMessage = { content: "", element: null };
    this.setSPLForm = setSPLForm
    this.setLogInfo = setLogInfo
    this.initializeWebSocket();
  }

  initializeWebSocket() {
    this.socket.addEventListener("open", () => {
      console.log("RefactorController Connected");
      this.sendMessage();
    });

    this.socket.addEventListener("message", (event) => {
      try {
        const messagePart = event.data;
        // 解析 JSON

        if (messagePart === "__END_OF_RESPONSE__") {
          this.setLogInfo("END\n")
          this.ongoingServerMessage = { content: "", element: null };
          this.close();
        } else {
          const response = JSON.parse(messagePart)
          if (response.type === 'logInfo' ) {
            this.setLogInfo(response.content)
          }else {
            console.log(response.content)
            this.setSPLForm(response.content)
          }
        }

        // 更新当前步骤
      } catch (error) {
        // this.setLogInfo("Error parsing message RefactorController: ", error);
      }
    });

    this.socket.addEventListener("close", () => {
      console.log("WebSocket Disconnected Refactor");
    });

    this.socket.addEventListener("error", (event) => {
      console.error("WebSocket Error Compiler: ", event);
    });
  }
  sendMessage() {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.setLogInfo("Refactor Form...\n")
        // console.log("Compiler Message");
        this.socket.send("1");
    }
  }
  close() {
    this.socket.close();
  }
}

export class AIChainRunController {
  constructor(agent_uuid, setMessages, agentType='tool') {
    this.agent_uuid = agent_uuid;
    this.ongoingServerMessage = { content: [], element: null };
    this.setMessages = setMessages;
    this.agentType = agentType
    this.connect();
  }

  connect() {
    this.socket = new WebSocket(`${url}ws/sapperchain/RunChain?agent_uuid=${this.agent_uuid}&mode=run&type=${this.agentType}`);

    this.socket.addEventListener('open', () => {
      console.log('WebSocket Connected');
    });

    this.socket.addEventListener('message', (event) => {
      const messagePart = event.data;
      if (messagePart === "__END_OF_RESPONSE__") {
        // Server message is complete, reset the ongoing server message
        this.ongoingServerMessage = { content: [], element: null };
      } else {
        // Server message is ongoing
        if (!this.ongoingServerMessage.element) {
          // If there's no ongoing element, create one
          this.ongoingServerMessage.element = { contents: [], role: "system" };
          this.setMessages(this.ongoingServerMessage.element);
        }
        // Update the content of the ongoing server message
        // if(JSON.parse(messagePart)['role'] === 'progress'){
          this.ongoingServerMessage.content = [];
        // }
        this.ongoingServerMessage.content.push(JSON.parse(messagePart));
        this.ongoingServerMessage.element.contents = [...this.ongoingServerMessage.content];
        // Trigger a state update to render the updated message
        this.setMessages(this.ongoingServerMessage.element);
      }
    });

    this.socket.addEventListener('close', () => {
      console.log("WebSocket connection closed");
    });

    this.socket.addEventListener('error', (event) => {
      console.error('WebSocket Error: ', event);
    });
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
      this.socket = null; // 清除现有的socket实例
    }
  }
}

export class AIChainDebugController {
  constructor(agent_uuid, setMessages, mode='run', handleNext = () =>{}, query, index) {
    this.agent_uuid = agent_uuid;
    this.ongoingServerMessage = { content: [], element: null };
    this.setMessages = setMessages;
    this.mode = mode
    this.query = query
    this.handleNext = handleNext
    this.index = index
    this.connect();
  }

  connect() {
    this.socket = new WebSocket(`${url}ws/sapperchain/RunChain?agent_uuid=${this.agent_uuid}&mode=${this.mode}`);

    this.socket.addEventListener('open', () => {
      console.log('WebSocket Connected');
      this.sendMessage();
    });

    this.socket.addEventListener('message', (event) => {
      const messagePart = event.data;
      console.log(messagePart)
      if (messagePart === "__END_OF_RESPONSE__") {
        // Server message is complete, reset the ongoing server message
        this.handleNext(this.ongoingServerMessage.element.contents);
        this.ongoingServerMessage = { content: [], element: null };
      } else {
        // Server message is ongoing
        if (!this.ongoingServerMessage.element) {
          // If there's no ongoing element, create one
          this.ongoingServerMessage.element = { contents: [], role: "system" };
          this.setMessages(this.ongoingServerMessage.element, this.index);
        }
        // Update the content of the ongoing server message
        // if(JSON.parse(messagePart)['role'] === 'progress'){
          this.ongoingServerMessage.content = [];
        // }
        this.ongoingServerMessage.content.push(JSON.parse(messagePart));
        this.ongoingServerMessage.element.contents = [...this.ongoingServerMessage.content];
        // Trigger a state update to render the updated message
        this.setMessages(this.ongoingServerMessage.element, this.index);
      }
    });

    this.socket.addEventListener('close', () => {
      console.log("WebSocket connection closed");
    });

    this.socket.addEventListener('error', (event) => {
      console.error('WebSocket Error: ', event);
    });
  }

  sendMessage() {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      // console.log("Compiler Message");
      this.socket.send(this.query);
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
      this.socket = null; // 清除现有的socket实例
    }
  }
}

export class SPLRunController {
  constructor(agent_uuid, setMessages) {
    this.socket = new WebSocket(`${url}ws/sapperchain/runspl?agent_uuid=${agent_uuid}`);
    this.ongoingServerMessage = { content: "", element: null };
    this.setMessages = setMessages;

    this.initializeWebSocket();
  }

  initializeWebSocket() {
    this.socket.addEventListener('open', () => {
      console.log('WebSocket Connected');
    });

    this.socket.addEventListener('message', (event) => {
      const messagePart = event.data;
      if (messagePart === "__END_OF_RESPONSE__") {
        // Server message is complete, reset the ongoing server message
        this.ongoingServerMessage = { content: [], element: null };
      } else {
        // Server message is ongoing
        if (!this.ongoingServerMessage.element) {
          // If there's no ongoing element, create one
          this.ongoingServerMessage.element = { contents: [{'type': 'text', 'content': ""}], role: "system" };
          this.setMessages(prevMessages => [...prevMessages, this.ongoingServerMessage.element]);
        }
        // Update the content of the ongoing server message
        this.ongoingServerMessage.content += messagePart;
        console.log(this.ongoingServerMessage.content)
        this.ongoingServerMessage.element.contents[0]['content'] = this.ongoingServerMessage.content;

        // Trigger a state update to render the updated message
        this.setMessages(prevMessages => [...prevMessages]);
      }
    });

    this.socket.addEventListener('close', () => {
      console.log('WebSocket Disconnected');
    });

    this.socket.addEventListener('error', (event) => {
      console.error('WebSocket Error: ', event);
    });
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      console.log(message)
      const data = JSON.parse(message); // 假设 jsonString 是您的 JSON 数据的字符串表示
      const textContents = data[data.length - 1]['contents']
        .filter(item => item["type"] === "text")
        .map(item => item["content"]);

      // 使用 join 方法将所有提取出的文本内容拼接在一起
      const combinedText = textContents.join(' ');

      // 输出结果
      console.log(combinedText);
      this.socket.send(combinedText);
    }
  }

  close() {
    this.socket.close();
  }
}
